<template>
  <div>
    <PageWrapper contentBackground contentClass="p-4">
      <div class="flex justify-between">
        <span>{{ title }}</span>
        <div class="flex justify-between">
          <Select
            v-model:value="selectValue"
            class="w-200px mr-15px"
            :options="selectOption"
            :bordered="false"
          ></Select>
          <TimeFiltering @time-filter-value="getTimeFilterValue" />
          <Tooltip title="更新图表" class="ml-15px mr-15px">
            <Icon icon="ant-design:picture-filled" size="25" color="#0960BD" />
          </Tooltip>
          <Button size="small" class="mt-2px" mr-15px>
            <Icon icon="ant-design:edit-filled" color="#0960BD" /> Edit Mode</Button
          >
          <Tooltip title="导出仪表盘" class="ml-15px mr-15px">
            <Icon icon="material-symbols:download-2" size="25" color="#0960BD" />
          </Tooltip>
        </div>
      </div>
    </PageWrapper>
    <div class="pl-4 flex">
      <EchartsCard :echarts-data="echartsTimeSeries" class="w-1/3 p-2" />
      <EnergyEcharts :echarts-data="echartsEnergy" class="w-1/3 p-2" />
      <EchartsCard :echarts-data="echartsVoltage" class="w-1/3 p-2" />
    </div>
    <EchartsTable class="pl-4" />
  </div>
</template>

<script setup lang="ts">
  import EchartsTable from './EchartsTable.vue';
  import EchartsCard from './EchartsCard.vue';
  import EnergyEcharts from './EnergyEcharts.vue';
  import Icon from '/@/components/Icon';
  import TimeFiltering from '/@/components/thingsborad/sharedComponents/modules/TimeFiltering.vue';
  import { useRoute } from 'vue-router';
  import { PageWrapper } from '/@/components/Page';
  import { getDashboard, apiDashboard } from '/@/api/thingsborad/dashboards/dashboard';
  import { onMounted, ref } from 'vue';
  import { Select, Tooltip, Button } from 'ant-design-vue';
  import { useWebSocket } from '@vueuse/core';
  import dayjs from 'dayjs';
  //接收路由传递的参数
  const route = useRoute();
  let dashboardValue = ref<any>();
  let title = ref<string>();
  let selectValue = ref<any>();
  let selectOption = ref<Array<any>>([]);
  let echartsTimeSeries = ref<any>({
    title: '时间序列折线图',
    echartsList: [
      {
        title: '总能量',
        data: [],
      },
      {
        title: '无功功率',
        data: [],
      },
      {
        title: '有功能量',
        data: [],
      },
    ],
  });
  let echartsEnergy = ref<any>({
    title: '能量占比',
    echartsList: [
      {
        value: 1048,
        name: '无功能量',
      },
      {
        value: 735,
        name: '有功能量',
      },
    ],
  });
  let echartsVoltage = ref<any>({
    title: '时间序列折线图',
    echartsList: [
      {
        title: '总能量',
        data: [],
      },
      {
        title: '电压',
        data: [],
      },
    ],
  });
  let send1 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              entityType: 'DEVICE',
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
            },
          },
          pageLink: {
            pageSize: 1024,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [],
        },
        cmdId: 1,
      },
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              entityType: 'DEVICE',
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
            },
          },
          pageLink: {
            pageSize: 1024,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [],
        },
        cmdId: 2,
      },
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              entityType: 'DEVICE',
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
            },
          },
          pageLink: {
            pageSize: 1,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [
            {
              type: 'TIME_SERIES',
              key: '温度',
            },
          ],
        },
        cmdId: 3,
      },
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              entityType: 'DEVICE',
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
            },
          },
          pageLink: {
            pageSize: 1024,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [],
        },
        cmdId: 6,
      },
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              entityType: 'DEVICE',
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
            },
          },
          pageLink: {
            pageSize: 1024,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [
            {
              type: 'TIME_SERIES',
              key: '无功能量',
            },
            {
              type: 'TIME_SERIES',
              key: '有功能量',
            },
          ],
        },
        cmdId: 7,
      },
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
              entityType: 'DEVICE',
            },
          },
          pageLink: {
            pageSize: 1024,
            page: 0,
            sortOrder: {
              key: {
                type: 'ENTITY_FIELD',
                key: 'createdTime',
              },
              direction: 'DESC',
            },
          },
          entityFields: [
            {
              type: 'ENTITY_FIELD',
              key: 'name',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'label',
            },
            {
              type: 'ENTITY_FIELD',
              key: 'additionalInfo',
            },
          ],
          latestValues: [],
        },
        cmdId: 9,
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              entityType: 'DEVICE',
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
            },
          },
          pageLink: {
            page: 0,
            pageSize: 10,
            textSearch: null,
            typeList: [],
            severityList: [],
            statusList: [],
            searchPropagatedAlarms: false,
            sortOrder: {
              key: {
                key: 'createdTime',
                type: 'ALARM_FIELD',
              },
              direction: 'DESC',
            },
            timeWindow: 2592000000,
          },
          alarmFields: [
            {
              type: 'ALARM_FIELD',
              key: 'createdTime',
            },
            {
              type: 'ALARM_FIELD',
              key: 'originator',
            },
            {
              type: 'ALARM_FIELD',
              key: 'type',
            },
            {
              type: 'ALARM_FIELD',
              key: 'severity',
            },
            {
              type: 'ALARM_FIELD',
              key: 'status',
            },
            {
              type: 'ALARM_FIELD',
              key: 'assignee',
            },
          ],
          entityFields: [],
          latestValues: [],
        },
        cmdId: 4,
      },
    ],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [
      {
        query: {
          entityFilter: {
            type: 'singleEntity',
            singleEntity: {
              id: '527da070-dd24-11ee-bd5d-eb7b38a2de3e',
              entityType: 'DEVICE',
            },
          },
        },
        cmdId: 8,
      },
    ],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [
      {
        query: {
          statusList: ['ACTIVE', 'ACK'],
          searchPropagatedAlarms: false,
          assigneeId: null,
        },
        cmdId: 5,
      },
    ],
    alarmCountUnsubscribeCmds: [],
  };
  let send2 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 1,
        tsCmd: {
          keys: ['总能量', '无功功率', '有功能量'],
          startTs: 1708322400000,
          timeWindow: 2599200000,
          interval: 7200000,
          limit: 361,
          agg: 'AVG',
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  let send3 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 2,
        tsCmd: {
          keys: ['电压', '总能量'],
          startTs: 1708329600000,
          timeWindow: 2599200000,
          interval: 7200000,
          limit: 361,
          agg: 'AVG',
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  let send4 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 3,
        tsCmd: {
          keys: ['温度'],
          startTs: 1710832800000,
          timeWindow: 86700000,
          interval: 300000,
          limit: 289,
          agg: 'AVG',
        },
        latestCmd: {
          keys: [
            {
              type: 'TIME_SERIES',
              key: '温度',
            },
          ],
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  let send5 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 6,
        tsCmd: {
          keys: ['无功能量', '有功能量'],
          startTs: 1710832800000,
          timeWindow: 86700000,
          interval: 300000,
          limit: 289,
          agg: 'AVG',
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  let send6 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 7,
        latestCmd: {
          keys: [
            {
              type: 'TIME_SERIES',
              key: '无功能量',
            },
            {
              type: 'TIME_SERIES',
              key: '有功能量',
            },
          ],
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  let send7 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 9,
        tsCmd: {
          keys: [
            '产品ID',
            '设备ID',
            '设备名称',
            '断路器开关',
            '功率因数',
            '开关次数',
            '电流',
            '电压',
          ],
          startTs: 1710833069000,
          timeWindow: 86401000,
          interval: 1000,
          limit: 200,
          agg: 'NONE',
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  let send8 = {
    attrSubCmds: [],
    tsSubCmds: [],
    historyCmds: [],
    entityDataCmds: [
      {
        cmdId: 3,
        tsCmd: {
          keys: [
            '产品ID',
            '断路器开关',
            '开关次数',
            '设备ID',
            '通信状态',
            '设备时间戳',
            '设备名称',
            '设备编码',
            '消息ID',
            '消息类型',
          ],
          startTs: 1708333873000,
          timeWindow: 2592001000,
          interval: 1000,
          limit: 200,
          agg: 'NONE',
        },
      },
    ],
    entityDataUnsubscribeCmds: [],
    alarmDataCmds: [],
    alarmDataUnsubscribeCmds: [],
    entityCountCmds: [],
    entityCountUnsubscribeCmds: [],
    alarmCountCmds: [],
    alarmCountUnsubscribeCmds: [],
  };
  const wsUrl = `ws://${import.meta.env.VITE_IP_PORT}/api/ws/plugins/telemetry?token=`;
  const token: any = localStorage.getItem('jwt_token');

  const { data, send } = useWebSocket(`${wsUrl}${token}`, {
    autoClose: false,
    autoReconnect: false,
    heartbeat: false,
    onConnected: () => console.log('onConnected'),
    onDisconnected: () => console.log('onDisconnected'),
    onError: () => console.log('onError'),
    onMessage: () => {
      let res = JSON.parse(data.value);
      if (res.cmdUpdateType === 'ENTITY_DATA' && res.update !== null && res.cmdId === 1) {
        Object.keys(res.update[0].timeseries).forEach((keys) => {
          if (keys === '总能量') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsTimeSeries.value.echartsList[0].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          } else if (keys === '无功功率') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsTimeSeries.value.echartsList[1].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          } else if (keys === '有功能量') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsTimeSeries.value.echartsList[2].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          }
        });
      }

      if (res.cmdUpdateType === 'ENTITY_DATA' && res.update !== null && res.cmdId === 6) {
      }
      echartsEnergy.value.echartsList[0].value = 21.09;
      echartsEnergy.value.echartsList[1].value = 945.09;
      if (res.cmdUpdateType === 'ENTITY_DATA' && res.update !== null && res.cmdId === 2) {
        Object.keys(res.update[0].timeseries).forEach((keys) => {
          if (keys === '总能量') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsVoltage.value.echartsList[0].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          } else if (keys === '电压') {
            res.update[0].timeseries[keys].forEach((item) => {
              echartsVoltage.value.echartsList[1].data.push([
                dayjs(item.ts).format('YYYY-MM-DD HH:mm:ss'),
                item.value,
              ]);
            });
          }
        });
      }
    },
  });
  onMounted(() => {
    selectValue.value = route.params.id;
    getApiDashboard(route.params.id);
    getDashboardSelect();
    send(JSON.stringify(send1));
    send(JSON.stringify(send2));
    send(JSON.stringify(send3));
    send(JSON.stringify(send4));
    send(JSON.stringify(send5));
    send(JSON.stringify(send6));
    send(JSON.stringify(send7));
    send(JSON.stringify(send8));
  });

  const getApiDashboard = async (id: any) => {
    try {
      let dashboardData = await apiDashboard(id);
      dashboardValue.value = dashboardData;
      title.value = dashboardValue.value.title;
    } catch (error) {}
  };
  const getDashboardSelect = async () => {
    try {
      let params: any = {
        pageSize: 100,
        page: 0,
      };
      let dashboardSelect = await getDashboard(params);
      dashboardSelect.data.forEach((item) => {
        selectOption.value.push({
          value: item.id.id,
          label: item.title,
        });
      });
    } catch (error) {}
  };
  const getTimeFilterValue = (_timestamp: any) => {};
</script>
